import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
  NzCheckboxModule,
  NzCheckBoxOptionInterface,
} from 'ng-zorro-antd/checkbox';
import { NzGridModule } from 'ng-zorro-antd/grid';

@Component({
  selector: 'app-checkbox-group-wrap',
  standalone: true,
  imports: [NzCheckboxModule, FormsModule, NzGridModule],
  template: `<div class="demo">
    <nz-checkbox-wrapper>
      <nz-row>
        <nz-col nzSpan="12">
          <label
            nz-checkbox
            [ngModel]="isAllSelected"
            (ngModelChange)="handleSelectAll($event)"
            [nzIndeterminate]="indeterminate"
          >
            全选
          </label>
        </nz-col>
      </nz-row>
      <nz-row>
        @for (opt of opts; track $index) {
        <nz-col nzSpan="6">
          <label
            nz-checkbox
            [ngModel]="isSelected(opt)"
            (ngModelChange)="handleSelectItem(opt, $event)"
          >
            {{ opt }}
          </label>
        </nz-col>
        }
      </nz-row>
    </nz-checkbox-wrapper>
  </div> `,
  styles: ``,
})
export class CheckboxGroupWrapComponent implements OnInit {
  private _isAllSelected = false;
  public get isAllSelected() {
    return this._isAllSelected;
  }

  private _indeterminate = false;
  public get indeterminate() {
    return this._indeterminate;
  }

  opts: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
  selects: string[] = ['C'];

  isSelected(item: string): boolean {
    return this.selects.includes(item);
  }

  ngOnInit(): void {
    this.updateSelectAllState();
  }

  handleSelectAll(checked: boolean): void {
    if (checked) {
      this.selects = [...this.opts];
    } else {
      this.selects = [];
    }
    this.updateSelectAllState();
  }

  handleSelectItem(item: string, checked: boolean): void {
    if (checked) {
      this.selects = [...this.selects, item];
    } else {
      this.selects = this.selects.filter((i) => i !== item);
    }
    this.updateSelectAllState();
  }

  private updateSelectAllState() {
    this._isAllSelected = this.selects.length === this.opts.length;
    this._indeterminate = this.selects.length > 0 && !this._isAllSelected;
  }
}
